<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTTPS连接测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
            max-width: 800px;
            margin: 0 auto;
        }
        .test-section {
            margin: 20px 0;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 8px;
        }
        button {
            padding: 10px 20px;
            margin: 5px;
            border: none;
            border-radius: 5px;
            background: #007bff;
            color: white;
            cursor: pointer;
        }
        button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        .error {
            color: red;
            margin: 10px 0;
        }
        .success {
            color: green;
            margin: 10px 0;
        }
        .info {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
        }
        pre {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 5px;
            overflow-x: auto;
        }
    </style>
</head>
<body>
    <h1>浏览器插件HTTPS连接测试</h1>
    
    <div class="test-section">
        <h2>1. 测试HTTPS连接</h2>
        <button onclick="testHttpsConnection()">测试HTTPS服务器连接</button>
        <div id="https-result"></div>
    </div>

    <div class="test-section">
        <h2>2. 测试配对API</h2>
        <button onclick="testPairingAPI()">测试配对API</button>
        <div id="pairing-result"></div>
    </div>

    <div class="test-section">
        <h2>3. 测试WebSocket连接</h2>
        <button onclick="testWebSocket()">测试WebSocket连接</button>
        <div id="websocket-result"></div>
    </div>

    <script>
        const servers = [
            'https://localhost:3001',
            'https://127.0.0.1:3001',
            'https://192.168.3.17:3001'
        ];

        async function testHttpsConnection() {
            const resultDiv = document.getElementById('https-result');
            resultDiv.innerHTML = '<div class="info">正在测试HTTPS连接...</div>';

            for (const server of servers) {
                try {
                    console.log(`测试连接: ${server}`);
                    const response = await fetch(`${server}/health`, {
                        method: 'GET',
                        headers: {
                            'Accept': 'application/json'
                        }
                    });

                    if (response.ok) {
                        const data = await response.json();
                        resultDiv.innerHTML += `<div class="success">✅ ${server} - 连接成功</div>`;
                        resultDiv.innerHTML += `<pre>${JSON.stringify(data, null, 2)}</pre>`;
                        return server; // 返回第一个成功的服务器
                    } else {
                        resultDiv.innerHTML += `<div class="error">❌ ${server} - HTTP ${response.status}</div>`;
                    }
                } catch (error) {
                    console.error(`连接失败 ${server}:`, error);
                    resultDiv.innerHTML += `<div class="error">❌ ${server} - ${error.message}</div>`;
                }
            }

            resultDiv.innerHTML += '<div class="error">❌ 所有服务器连接失败</div>';
            return null;
        }

        async function testPairingAPI() {
            const resultDiv = document.getElementById('pairing-result');
            resultDiv.innerHTML = '<div class="info">正在测试配对API...</div>';

            for (const server of servers) {
                try {
                    console.log(`测试配对API: ${server}`);
                    const response = await fetch(`${server}/api/pairing/generate`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Accept': 'application/json'
                        },
                        body: JSON.stringify({
                            deviceId: 'test-browser-' + Date.now(),
                            deviceType: 'browser',
                            deviceName: 'Test Browser'
                        })
                    });

                    if (response.ok) {
                        const data = await response.json();
                        resultDiv.innerHTML += `<div class="success">✅ ${server} - 配对API成功</div>`;
                        resultDiv.innerHTML += `<pre>${JSON.stringify(data, null, 2)}</pre>`;
                        return;
                    } else {
                        const errorText = await response.text();
                        resultDiv.innerHTML += `<div class="error">❌ ${server} - HTTP ${response.status}: ${errorText}</div>`;
                    }
                } catch (error) {
                    console.error(`配对API失败 ${server}:`, error);
                    resultDiv.innerHTML += `<div class="error">❌ ${server} - ${error.message}</div>`;
                }
            }

            resultDiv.innerHTML += '<div class="error">❌ 所有服务器配对API失败</div>';
        }

        async function testWebSocket() {
            const resultDiv = document.getElementById('websocket-result');
            resultDiv.innerHTML = '<div class="info">正在测试WebSocket连接...</div>';

            const wsServers = [
                'wss://192.168.3.17:3001',
                'ws://192.168.3.17:3001',
                'wss://localhost:3001',
            ];

            for (const wsServer of wsServers) {
                try {
                    resultDiv.innerHTML += `<div class="info">尝试连接: ${wsServer}</div>`;
                    console.log(`测试WebSocket: ${wsServer}`);
                    const ws = new WebSocket(wsServer);

                    await new Promise((resolve, reject) => {
                        const timeout = setTimeout(() => {
                            ws.close();
                            reject(new Error('连接超时 (5秒)'));
                        }, 5000);

                        ws.onopen = () => {
                            clearTimeout(timeout);
                            resultDiv.innerHTML += `<div class="success">✅ ${wsServer} - WebSocket连接成功！</div>`;
                            ws.close();
                            resolve();
                        };

                        ws.onerror = (error) => {
                            clearTimeout(timeout);
                            console.error(`WebSocket error for ${wsServer}:`, error);
                            reject(new Error('连接发生错误'));
                        };
                    });

                    // 只要有一个成功就停止
                    return; 
                } catch (error) {
                    console.error(`WebSocket连接失败 ${wsServer}:`, error);
                    resultDiv.innerHTML += `<div class="error">❌ ${wsServer} - ${error.message}</div>`;
                }
            }

            resultDiv.innerHTML += '<div class="error">❌ 所有WebSocket连接都失败了</div>';
        }

        // 页面加载时自动测试HTTPS连接
        window.addEventListener('load', () => {
            testHttpsConnection();
        });
    </script>
</body>
</html>
